﻿#include "ExportParamDbdlg.h"
#include "ui_ExportParamDbdlg.h"
#include <QByteArray>
#include <QDir>
#include <QFileDialog>
#include <QMessageBox>


ExportParamDbdlg::ExportParamDbdlg(QWidget *parent) : QDialog(parent), ui(new Ui::ExportParamDbdlg)
{
    ui->setupUi(this);
	m_pSqLDB = NULL;
	m_Timer1 = NULL;
	setFixedSize(551, 301);
	setWindowTitle(QString::fromLocal8Bit("导出终端参数数据库文件"));
	ui->pAfirmPushBtn->setText(QString::fromLocal8Bit("导  出"));
	ui->pCacellPushBtn->setText(QString::fromLocal8Bit("返  回"));
	ui->pEdt_DevicedbDir->setReadOnly(true);
	ui->pYxNumEdit->setReadOnly(true);
	ui->pYcNumEdit->setReadOnly(true);
	ui->pYkNumEdit->setReadOnly(true);
	ui->pYmNumEdit->setReadOnly(true);
	ui->pBhycNumEdit->setReadOnly(true);
	ui->pParaNumEdit->setReadOnly(true);
	ui->pPrecNumEdit->setReadOnly(true);
	ui->pRybNumEdit->setReadOnly(true);
	ui->pDoNumEdit->setReadOnly(true);
	ui->pProgressBar->setRange(0,100);
	
	m_bakFileAllNameStr = QString::fromLocal8Bit("..\\..\\exportdb\\devicedb.db");
	ui->pEdt_DevicedbDir->setText(m_bakFileAllNameStr);

	m_DevModelId = 0;
	m_YxNum = 0;
	m_YcNum = 0;
	m_YkNum = 0;
	m_YmNum = 0;
	m_SetNum = 0;
	m_BhycNum = 0;
	m_PrecNum = 0;
	m_RybNum = 0;
	
	m_Timer1 = new QTimer(this);
	if (m_Timer1)
	{
		connect(m_Timer1, SIGNAL(timeout()), this, SLOT(TimerProc_Main()));
	}

	m_pSqLDB = new SqLiteDB;
	
	GetDeviceModelInfo();

	connect(ui->pBtn_SetDbName, SIGNAL(clicked()), this, SLOT(OnSetDBDir()));
	connect(ui->pAfirmPushBtn, SIGNAL(clicked()), this, SLOT(ExportDeviceDB()));
	connect(ui->pCacellPushBtn, SIGNAL(clicked()), this, SLOT(close()));
	
	setModal(true);
}

ExportParamDbdlg::~ExportParamDbdlg()
{
	m_ColInfo.ReleasColumnInfo();
    delete ui;
	if (m_pSqLDB)
	{
		m_pSqLDB->CloseCurDB();
		delete m_pSqLDB;
		m_pSqLDB =NULL;
	}
}

void ExportParamDbdlg::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ExportParamDbdlg::OnSetDBDir()
{
	if (!m_pSqLDB)
	{
		return ;
	}
	m_pSqLDB->CloseCurDB();
	
	int Ret = 0;
	QString TitleStr = QString::fromLocal8Bit("选择装置数据库文件...");
	QString bakfileDirStr = QString::fromLocal8Bit("..\\..\\exportdb\\");
	//QString filterStr = QString::fromLocal8Bit("*.db");
	QString  NewDirStr;
//	bakFileAllNameStr = QFileDialog::getOpenFileName(this, TitleStr, bakfileDirStr,filterStr);
	NewDirStr = QFileDialog::getExistingDirectory(this, TitleStr, bakfileDirStr);
	m_bakFileAllNameStr = NewDirStr+QString::fromLocal8Bit("devicedb.db");
	ui->pEdt_DevicedbDir->setText(m_bakFileAllNameStr);
	if ( m_bakFileAllNameStr.toLocal8Bit().length()>260)
	{
		QMessageBox::information(this, QString::fromLocal8Bit("Warn"), QString::fromLocal8Bit("数据库文件路径过长！\r\n"));
	}
}

int	ExportParamDbdlg::OpenDeviceDB()
{
	if (m_bakFileAllNameStr.length()<=0 && m_bakFileAllNameStr.toLocal8Bit().length()>260)
	{
		return -1;
	}

	char DbName[260];
	memset(DbName, 0, 260);
	sprintf(DbName, "%s",m_bakFileAllNameStr.toLocal8Bit().data());
	m_pSqLDB->Init_DB(true, DbName, 260);
	int Ret = m_pSqLDB->OpenCurDB();
	
	return Ret;
}

//	获取设备模板信息
int ExportParamDbdlg::GetDeviceModelInfo()
{
	char *pBuff = NULL;
	int	Buff_len = 0;
	int	Ret = 0;
	unsigned int	ItemData =0;
	QString ItemText;
	QListWidgetItem *pListItem = NULL;

	QSize size(200, 19);
	Ret = g_DbCfgFunObj.GetRecordBuffbyAppType_TableId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVMODEL_INFO, pBuff, &Buff_len, false);
	if (Ret>0 && pBuff && Buff_len>0)
	{
		for (int i=0; i<Ret; i++)
		{
			ItemData = ((rDevModel_Info *)pBuff)[i].ID;
		}
	}
	if (pBuff)
	{
		delete [](unsigned char*)pBuff;
		pBuff = NULL;
	}
	return 1;
}

//	显示设备模板信息
void ExportParamDbdlg::InitDevModeInfoShow()
{
	m_YxNum = 0;
	m_YcNum = 0;
	m_YkNum = 0;
	m_YmNum = 0;
	m_SetNum = 0;
	m_BhycNum = 0;
	m_ParaNum = 0;
	m_PrecNum = 0;
	m_RybNum = 0;
	if (m_DevModelId > 0)
	{
		g_DbCfgFunObj.GetRecordNumbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVMODEL_YX,   m_DevModelId+PARENT_OFFSET*TABLE_RDEVMODEL_INFO, &m_YxNum  );
		g_DbCfgFunObj.GetRecordNumbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVMODEL_YC,   m_DevModelId+PARENT_OFFSET*TABLE_RDEVMODEL_INFO, &m_YcNum  );
		g_DbCfgFunObj.GetRecordNumbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVMODEL_YK,   m_DevModelId+PARENT_OFFSET*TABLE_RDEVMODEL_INFO, &m_YkNum  );
		g_DbCfgFunObj.GetRecordNumbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVMODEL_YM,   m_DevModelId+PARENT_OFFSET*TABLE_RDEVMODEL_INFO, &m_YmNum  );
		g_DbCfgFunObj.GetRecordNumbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVMODEL_SET,  m_DevModelId+PARENT_OFFSET*TABLE_RDEVMODEL_INFO, &m_SetNum );
		g_DbCfgFunObj.GetRecordNumbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVMODEL_BHYC, m_DevModelId+PARENT_OFFSET*TABLE_RDEVMODEL_INFO, &m_BhycNum);
		g_DbCfgFunObj.GetRecordNumbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVMODEL_PARA, m_DevModelId+PARENT_OFFSET*TABLE_RDEVMODEL_INFO, &m_ParaNum);
		g_DbCfgFunObj.GetRecordNumbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVMODEL_PREC, m_DevModelId+PARENT_OFFSET*TABLE_RDEVMODEL_INFO, &m_PrecNum);
		g_DbCfgFunObj.GetRecordNumbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVMODEL_RYB,  m_DevModelId+PARENT_OFFSET*TABLE_RDEVMODEL_INFO, &m_RybNum );
	}
	ui->pYxNumEdit->setText(QString::fromLocal8Bit("%1").arg(m_YxNum));
	ui->pYcNumEdit->setText(QString::fromLocal8Bit("%1").arg(m_YcNum));
	ui->pYkNumEdit->setText(QString::fromLocal8Bit("%1").arg(m_YkNum));
	ui->pYmNumEdit->setText(QString::fromLocal8Bit("%1").arg(m_YmNum));
	ui->pSetNumEdit->setText(QString::fromLocal8Bit("%1").arg(m_SetNum));
	ui->pBhycNumEdit->setText(QString::fromLocal8Bit("%1").arg(m_BhycNum));
	ui->pParaNumEdit->setText(QString::fromLocal8Bit("%1").arg(m_ParaNum));
	ui->pPrecNumEdit->setText(QString::fromLocal8Bit("%1").arg(m_PrecNum));
	ui->pRybNumEdit->setText(QString::fromLocal8Bit("%1").arg(m_RybNum));
}

//设置进度条显示
void ExportParamDbdlg::SetPogressShow(int CurValue, int MaxValue)
{
	if (MaxValue<=0)
	{
		MaxValue = 100;
		CurValue =0;
		ui->pProgressBar->setMaximum(MaxValue);
		ui->pProgressBar->setValue(CurValue);
		MaxValue = 100;
		CurValue =100;
		ui->pProgressBar->setMaximum(MaxValue);
		ui->pProgressBar->setValue(CurValue);
	}else
	{
		ui->pProgressBar->setMaximum(MaxValue);
		ui->pProgressBar->setValue(CurValue);
	}
}

//	判断设备参数
void ExportParamDbdlg::ExportDeviceDB()
{
	int result = 1;
	
	if (OpenDeviceDB()<=0)
	{
		QMessageBox::information(this, QString::fromLocal8Bit("Warn"), QString::fromLocal8Bit("数据库文件打开失败！\r\n"));
		return ;
	}
	if (!m_Timer1)
	{
		return ;
	}
	m_ExportStepNo = EXPORT_DB_STEP_CREATE_TABLE;
	m_TableNo = 0;
	m_TableMaxNum = TABLE_RPARAMS_VERS-TABLE_RPARAMS_SYS+1;

	ui->pAfirmPushBtn->setEnabled(false);
	m_Timer1->start(200);
	ui->pLabel_State->setText(QString::fromLocal8Bit("终端数据表创建过程中..."));
// 	if (result>0)
// 	{
// 		InsertDeviceParam();
// 		close();
// 	}
}

void ExportParamDbdlg::TimerProc_Main()
{
	if (m_Timer1)
	{
		m_Timer1->stop();
	}
	switch (m_ExportStepNo)
	{
	case EXPORT_DB_STEP_CREATE_TABLE:
		{
			CreateDeviceTable(m_TableNo);
			m_TableNo++;
			if (m_TableNo >= m_TableMaxNum)
			{
				m_TableNo = 0;
				m_ExportStepNo = EXPORT_DB_STEP_EXPORTDATA;
				ui->pLabel_State->setText(QString::fromLocal8Bit("终端数据表导出过程中..."));
			}
		}
		break;
	case EXPORT_DB_STEP_EXPORTDATA:
		{
			ExportDeviceTableData(m_TableNo);
			m_TableNo++;
			if (m_TableNo >= m_TableMaxNum)
			{
				m_TableNo = 0;
				m_TableMaxNum = TABLE_RDEVS_OUT/*TABLE_RDEVS_COMMU*/-TABLE_RDEVS_INFO+1;
				m_ExportStepNo = EXPORT_DB_STEP_CREATE_LDTABLE;
			}
		}
		break;
	case EXPORT_DB_STEP_CREATE_LDTABLE:
		{
			CreateLDeviceTable(m_TableNo);
			m_TableNo++;
			if (m_TableNo >= m_TableMaxNum)
			{
				m_TableNo = 0;
				m_ExportStepNo = EXPORT_DB_STEP_EXPORT_LDDATA;
				ui->pLabel_State->setText(QString::fromLocal8Bit("终端数据表导出过程中..."));
			}
		}
		break;
	case EXPORT_DB_STEP_EXPORT_LDDATA:
		{
			ExportLDeviceTableData(m_TableNo);
			m_TableNo++;
			if (m_TableNo >= m_TableMaxNum)
			{
				m_ExportStepNo = EXPORT_DB_STEP_FINISH;
			}
		}
		break;
	default:
		break;
	}

	SetPogressShow(m_TableNo, m_TableMaxNum);
	if (m_TableNo < m_TableMaxNum)
	{
		m_Timer1->start(200);
	}else
	{
		ui->pAfirmPushBtn->setEnabled(true);
		ui->pLabel_State->setText(QString::fromLocal8Bit("终端数据导出完成！"));
		QMessageBox::information(this,QString::fromLocal8Bit("导出终端配置"),QString::fromLocal8Bit("终端配置导出完成！"));
		accept();
	}
}

int	ExportParamDbdlg::CreateDeviceTable(int TableNo)
{
	int TableId = TABLE_RPARAMS_SYS+TableNo;
	if (TableId <= TABLE_RPARAMS_VERS)
	{
		g_DbCfgFunObj.CreateNewDevTable(m_pSqLDB, SYSTEM_TYPE_NSA_YD, TableId, true);
	}
	return 1;
}

int	ExportParamDbdlg::ExportDeviceTableData(int TableNo)
{
	int			 TableId = TABLE_RPARAMS_SYS+TableNo;
	char		 *pBuff = NULL;
	int			 buff_len = 0;
	int			 Ret = 0;
	char		 tableName[TABLE_ENG_NAME_LEN];
	unsigned int RecStartId = 0;
	QString			SqlStr;
	QString			InsertHeadSqlStr;
	QString			InsertValSqlStr;
	int				RecordLen = 0;
	int				NewRecordNum = 0;
	int				i=0;
	int				Result=0;

	memset(tableName, 0, TABLE_ENG_NAME_LEN);

	if (TableId <= TABLE_RPARAMS_VERS)
	{
		Ret = g_DbCfgFunObj.GetTableEngNamebyAppType_TableId(SYSTEM_TYPE_NSA_YD, TableId, tableName);
		if (Ret<=0)
		{
			return -1;
		}
		Ret = g_DbCfgFunObj.GetRecordBuffbyAppType_TableId(SYSTEM_TYPE_NSA_YD, TableId, pBuff, &buff_len,&RecordLen, true);
		if (Ret>0 && RecordLen>0 && pBuff)
		{
			m_ColInfo.InitColumnInfo(SYSTEM_TYPE_NSA_YD, TableId);
			if (!m_ColInfo.IsSafe())
			{
				m_ColInfo.ReleasColumnInfo();
				return -2;
			}

			g_DbCfgFunObj.GetInsertHeadSql(SYSTEM_TYPE_NSA_YD, TableId, tableName, InsertHeadSqlStr);

			SqlStr.clear();
			m_pSqLDB->BeginTransaction();
			for (i=0; i<Ret; i++)
			{
				//RecStartId =0;
				//g_DbCfgFunObj.GetNewFreeId_DeviceDB(m_pSqLDB, SYSTEM_TYPE_NSA_YD, TableId, RecStartId);
				//if ((PARENT_OFFSET-RecStartId)<Ret )
				//{
				//	break;
				//}
				//memcpy(pBuff+RecordLen*i, &(RecStartId), 4);
				g_DbCfgFunObj.GetValuesSql((char*)(pBuff+RecordLen*i), m_ColInfo.m_RecordLength, m_ColInfo.m_pColumnInfo,  m_ColInfo.m_pDataOffset,  m_ColInfo.m_columnNum, OPER_ROW_INSERT, InsertValSqlStr);
				if (InsertValSqlStr.length()<=0)
				{
					continue;
				}

					SqlStr = InsertHeadSqlStr+InsertValSqlStr;
					sprintf(m_Dsql, "%s", SqlStr.toLocal8Bit().data());
					Result = m_pSqLDB->DB_Modify(m_Dsql);
					if (Result<0)
					{
						if (pBuff)
						{
							delete [](char*)pBuff;
							pBuff = NULL;
						}
						QMessageBox::information(this, QString::fromLocal8Bit("组态"), QString::fromLocal8Bit("插入%1记录失败！").arg(QString::fromLocal8Bit(tableName)), QMessageBox::Ok | QMessageBox::Cancel);
						break;
					}
					SqlStr.clear();

				NewRecordNum++;
			}
			m_pSqLDB->CommitTransaction();

			m_ColInfo.ReleasColumnInfo();
		}
		if (pBuff)
		{
			free(pBuff);
			pBuff=NULL;
		}
	}
	return NewRecordNum;
}


int	ExportParamDbdlg::CreateLDeviceTable(int TableNo)
{
	int TableId = TABLE_RDEVS_INFO+TableNo;
	if (TableId <= TABLE_RDEVS_OUT/*TABLE_RDEVS_COMMU*/)
	{
		g_DbCfgFunObj.CreateNewDevTable(m_pSqLDB, SYSTEM_TYPE_NSA_YD, TableId, true);
	}
	return 1;
}

int	ExportParamDbdlg::ExportLDeviceTableData(int TableNo)
{
	int			 TableId = TABLE_RDEVS_INFO+TableNo;
	char		 *pBuff = NULL;
	int			 buff_len = 0;
	int			 Ret = 0;
	char		 tableName[TABLE_ENG_NAME_LEN];
	unsigned int RecStartId = 0;
	QString			SqlStr;
	QString			InsertHeadSqlStr;
	QString			InsertValSqlStr;
	int				RecordLen = 0;
	int				NewRecordNum = 0;
	int				i=0;
	int				Result=0;

	memset(tableName, 0, TABLE_ENG_NAME_LEN);

	if (TableId <= TABLE_RDEVS_OUT/*TABLE_RDEVS_COMMU*/)
	{
		Ret = g_DbCfgFunObj.GetTableEngNamebyAppType_TableId(SYSTEM_TYPE_NSA_YD, TableId, tableName);
		if (Ret<=0)
		{
			return -1;
		}
		if (TABLE_RDEVS_INFO == TableId)
		{
			Ret = g_DbCfgFunObj.GetRecordBuffbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TableId, PARENT_OFFSET*TABLE_RPARAMS_TERMINAL, pBuff, &buff_len,&RecordLen, true);
		}else
		{
			Ret = g_DbCfgFunObj.GetRecordBuffbyAppType_TableId_TaskId(SYSTEM_TYPE_NSA_YD, TableId, PARENT_OFFSET*TABLE_RPARAMS_TERMINAL, pBuff, &buff_len,&RecordLen);
		}
	
		if (Ret>0 && RecordLen>0 && pBuff)
		{
			m_ColInfo.InitColumnInfo(SYSTEM_TYPE_NSA_YD, TableId);
			if (!m_ColInfo.IsSafe())
			{
				m_ColInfo.ReleasColumnInfo();
				return -2;
			}

			g_DbCfgFunObj.GetInsertHeadSql(SYSTEM_TYPE_NSA_YD, TableId, tableName, InsertHeadSqlStr);

			SqlStr.clear();
			m_pSqLDB->BeginTransaction();
			for (i=0; i<Ret; i++)
			{
				//RecStartId =0;
				//g_DbCfgFunObj.GetNewFreeId_DeviceDB(m_pSqLDB, SYSTEM_TYPE_NSA_YD, TableId, RecStartId);
				//if ((PARENT_OFFSET-RecStartId)<Ret )
				//{
				//	break;
				//}
				//memcpy(pBuff+RecordLen*i, &(RecStartId), 4);
				g_DbCfgFunObj.GetValuesSql((char*)(pBuff+RecordLen*i), m_ColInfo.m_RecordLength, m_ColInfo.m_pColumnInfo,  m_ColInfo.m_pDataOffset,  m_ColInfo.m_columnNum, OPER_ROW_INSERT, InsertValSqlStr);
				if (InsertValSqlStr.length()<=0)
				{
					continue;
				}

				SqlStr = InsertHeadSqlStr+InsertValSqlStr;
				sprintf(m_Dsql, "%s", SqlStr.toLocal8Bit().data());
				Result = m_pSqLDB->DB_Modify(m_Dsql);
				if (Result<0)
				{
					if (pBuff)
					{
						delete [](char*)pBuff;
						pBuff = NULL;
					}
					QMessageBox::information(this, QString::fromLocal8Bit("组态"), QString::fromLocal8Bit("插入%1记录失败！").arg(QString::fromLocal8Bit(tableName)), QMessageBox::Ok | QMessageBox::Cancel);
					break;
				}
				SqlStr.clear();

				NewRecordNum++;
			}
			m_pSqLDB->CommitTransaction();

			m_ColInfo.ReleasColumnInfo();
		}
		if (pBuff)
		{
			free(pBuff);
			pBuff=NULL;
		}
	}
	return NewRecordNum;
}
